import cerberus
from flask import request, jsonify
from app.Vendor.Code import Code
from app.Vendor.CustomErrorHandler import CustomErrorHandler


class BaseController:

    ''' 
    * 验证输入信息
    * @param  dict rules
    * @param  string error_msg
    * @return response
    '''

    def validateInput(self, rules, error_msg=None):
        v = cerberus.Validator(
            rules, error_handler=CustomErrorHandler(custom_messages=error_msg))
        #v = ObjectValidator(rules)
        #这边修改成json格式接收参数
        try:
            requests = request.values()
        except TypeError:
            requests = request.get_json()
        if (v.validate(requests)):  # validate
            return True
        error = {}
        error['msg'] = v.errors
        error['code'] = Code.BAD_REQUEST
        return self.json(error)

    ''' 
    * 验证输入信息根据字段名
    * @param  dict rules
    * @param  string error_msg
    * @return response
    '''

    def validateInputByName(self, name, rules, error_msg=None):
        v = cerberus.Validator(
            rules, error_handler=CustomErrorHandler(custom_messages=error_msg))
        #v = ObjectValidator(rules)
        #这边修改成json格式接收参数
        try:
            requests = request.values()
        except TypeError:
            requests = request.get_json()
        if (v.validate({name: requests[name]})):  # validate
            return requests
        error = {}
        error['msg'] = v.errors
        error['code'] = Code.BAD_REQUEST
        return self.json(error)

    '''
    * 返回Json数据
    * @param  dict body
    * @return json
    '''
    def json(self, body={}):
        return jsonify(body)

    '''
    * 返回错误信息
    * @param  msg string
    * @return json
    '''
    def error(self, msg=''):
        return self.json({'code': Code.BAD_REQUEST,  'msg': msg})

    '''
    * 返回token失效信息
    * @param  msg string
    * @return json
    '''
    def notAuth(self, msg=''):
        return self.json({'code': Code.NOT_AUTH,  'msg': msg})

    '''
    * 返回成功信息
    * @param  msg string
    * @return json
    '''
    def successData(self, data=''):
        return self.json({'code': Code.SUCCESS, 'data': data,'msg': 'ok'})


